
import paho.mqtt.client as mqtt
import json
import redis
from settings import (MQTT_HOST, MQTT_PORT, MQTT_CLIENT_CERT, MQTT_AUTH, MQTT_PASSWORD, MQTT_TOPIC, 
                      MQTT_RECEIVE_QUEUE, MQTT_SEND_QUEUE,
                      REDIS_HOST, REDIS_PORT, REDIS_DB
                      )


def send_mqtt_message(send_topic, message_json):

    '''
    :param send_topic: MQTT topic to publish message
    :param message_json: JSON message to be published : {"type": "test_message", "data": {"device_code": "1234567890", "message": "Hello, World!"}}
    :return: None
    '''

    client = mqtt.Client()
    client.tls_set(MQTT_CLIENT_CERT)
    client.username_pw_set(MQTT_AUTH, MQTT_PASSWORD)
    client.connect(MQTT_HOST, MQTT_PORT)
    client.publish(send_topic, message_json)
    client.disconnect()


def publish_message_to_redis(send_topic, message):
    '''
    :param send_topic: MQTT topic to publish message
    :param message: JSON message to be published : {"type": "test_message", "data": {"device_code": "1234567890", "message": "Hello, World!"}}
    :return: None
    '''

    message = {"send_topic": send_topic, "send_data": message}

    redis_client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
    redis_client.lpush(MQTT_SEND_QUEUE, json.dumps(message))


